﻿using System;
using System.Runtime.InteropServices;

namespace TGInspect
{
    public class RtTimer
    {
        [DllImport("kernel32.dll")]
		extern static short QueryPerformanceCounter(ref long x);
		[DllImport("kernel32.dll")]
		extern static short QueryPerformanceFrequency(ref long x);

		private long StartTime;
		private long StopTime;
		private long ClockFrequency;
		private long CalibrationTime;

		public RtTimer()
		{
			StartTime       = 0;
			StopTime        = 0;
			ClockFrequency  = 0;
			CalibrationTime = 0;
			Calibrate();
		}

		public void Calibrate()
		{
			QueryPerformanceFrequency(ref ClockFrequency);
			for(int i=0; i<1000; i++)
			{
                SetTime();
				Stop();
				CalibrationTime += StopTime - StartTime;
			}
			CalibrationTime /= 1000;
		}

		public void Reset()
		{
			StartTime = 0;
			StopTime  = 0;
		}

		public void SetTime()
		{
			QueryPerformanceCounter(ref StartTime);
		}

		public void Stop()
		{
			QueryPerformanceCounter(ref StopTime);
		}

		public uint GetElapsedTimeMs()
		{
            Stop();
			return (uint)(((StopTime - StartTime - CalibrationTime) * 1000000.0 / ClockFrequency) / 1000.0);
		}

        public bool IsTimeOverMs(uint time)
        {
            return (time > GetElapsedTimeMs());
        }


    }
}
